﻿using System;
using System.Collections;
using System.Web.UI.WebControls;

namespace Sunyi.Project.WebPoint.WebControl
{
    public class PagingGridView : GridView
    {
        private const string VewState_TotalCountKey = "VS_TotalCount";

        private int totalCount;

        public int TotalCount
        {
            get
            {
                return totalCount;
            }
            set
            {
                totalCount = value;

                this.EnableViewState = true;
                this.Page.EnableViewState = true;
                ViewState[VewState_TotalCountKey] = value;
            }
        }

        public int MaxPageIndex
        {
            get
            {
                int maxPageIndex = this.TotalCount / this.PageSize - 1;

                if (this.TotalCount % this.PageSize != 0) maxPageIndex++;

                return maxPageIndex;
            }
        }

        public override object DataSource
        {
            get
            {
                return base.DataSource;
            }
            set
            {
                base.DataSource = value;

                IList dataSource = value as IList;
                if (dataSource == null) return;

                if (this.TotalCount < dataSource.Count) this.TotalCount = dataSource.Count;

                if (this.TotalCount > dataSource.Count)
                {
                    // Add vitual records before the data source.
                    for (int i = 0; i < this.PageSize * this.PageIndex; i++) dataSource.Insert(i, null);

                    if (this.PageIndex < this.MaxPageIndex)
                    {
                        // Add vitual records after the data source.
                        for (int i = dataSource.Count; i < this.TotalCount; i++) dataSource.Insert(i, null);
                    }
                }
            }
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);

            if (ViewState[VewState_TotalCountKey] != null)
            {
                this.TotalCount = Int32.Parse(ViewState[VewState_TotalCountKey].ToString());
            }
        }
    }
}
